// index.js
const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    filePaths:[],
    fileIds:[],
    date:'2021-01-01',
    retitle:'',
    blogContent:'',
    reid:""
  },
  
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  //提交数据
  submitBlog:function(e){
    console.log("点了")
    var listPath = this.data.filePaths;
    var listIds = this.data.fileIds;
    var that = this
    //获取富文本编辑器里的内容
    this.editorContext.getContents({
      success:res=>{
        var a=0;
        //上传图片同时
        that.uploadImg(listPath,res.html)
      }
    })
  },

  //富文本编辑器初始化
  onEditorReady: function (e) {
    var that = this
    wx.createSelectorQuery().select("#contentEditor").context(res => {
      this.editorContext = res.context
      //判断是修改还是新增
      if(that.data.reid.length>0){
        db.collection('grlist').doc(that.data.reid).get({
          success: function(res) {
            // res.data 包含该记录的数据
            that.setData({
              date:res.data.editDate,
              retitle:res.data.retitle,
              blogContent:res.data.msg
            })
            that.editorContext.setContents({
              html:res.data.msg    //这里就是设置默认值的地方（html 后面给什么就显示什么）
                            //that.data.content 是我存在 data 里面的数据
                            //注意是 this 赋值的 that，如果用 this 就把上面的 function 改成箭头函数
            });
          }
        })        
      }

    }).exec()
  },

  //富文本处理
  format: function (e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    this.editorContext.format(name, value)
  },

  //插入图片
  insertImage: function (e) {
    var filePaths2 = this.data.filePaths;
    wx.chooseImage({
      count: 1,
      success: res=> {
        this.editorContext.insertImage({
          src: res.tempFilePaths[0], //可以换成云函数的 fileid
          data: {
            id: 'myImg'
          },
          width: '100%',
          success: function () {
            filePaths2.push(res.tempFilePaths[0])
          }
        })
      }
    })
  },

   getRandomCode:function(length) {
    if (length > 0) {
       var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
       var nums = "";
       for (var i = 0; i < length; i++) {
          var r = parseInt(Math.random() * 61);
          nums += data[r];
       }
       return nums;
    } else {
       return false;
    }
 },


  uploadImg: function(listPath,html) {
    var imgArrList = []
    var fileIds = this.data.fileIds
    var that = this
    console.log(listPath)
    listPath.forEach((item,index) => {
      var timestamp = that.getRandomCode(32)
      console.log(timestamp)
      wx.showLoading({
        title: '正在上传',
        mask:true
      })
      var promise =  new Promise((resolve,reject)=>{
      // 将图片上传至云存储空间
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: timestamp+"png",
        // 指定要上传的文件的小程序临时文件路径
        filePath: item,
        config: {
          env: this.data.envId
        },
        success:(result)=>{
          fileIds.push(result.fileID)
          resolve()
        }
      })
      
      }
      
  )
  imgArrList.push(promise)
}
  )
  Promise.all(imgArrList).then(res=>{
    console.log(456)
    var that = this
    if(imgArrList.length==0){
      console.log(imgArrList)
      fileIds.forEach((item,index)=>{
        console.log(listPath[index])
        console.log(item)
        html = html.replace(listPath[index],item)
      })
      that.setData({
        blogContent:html
      })
      that.testdb()
    }else{
      console.log(imgArrList)
      wx.hideLoading({
        success:(res)=>{
          fileIds.forEach((item,index)=>{
            console.log(listPath[index])
            console.log(item)
            html = html.replace(listPath[index],item)
          })
          that.setData({
            blogContent:html
          })
          that.testdb()
        }
      });
    }
    
  })
  },

  bind_put_title(e){
    this.setData({
      retitle:e.detail.value
    })
  },

  testdb: function() {
      // 初始化数据库
    // const db = wx.cloud.database();
    console.log(this.data.reid)
    if(this.data.reid.length>0){
      db.collection("grlist").doc(this.data.reid)
      .update({
          data:{
              retitle:this.data.retitle,
              msg:this.data.blogContent,
              editDate:this.data.date
          }
      }).then(res=>{
        wx.showToast({ title: '更新成功' });
        wx.redirectTo({
          url: '/pages/editor/editor'
          //url默认为本页面，所以需要退一层../
        })
      })
      
    }else{
      db.collection("grlist")
      .add({
          data:{
              retitle:this.data.retitle,
              msg:this.data.blogContent,
              editDate:this.data.date
          }
      }).then(res=>{
        console.log(res)
        wx.showToast({ title: '添加成功' });
        wx.redirectTo({
          url: '/pages/editor/editor'
          //url默认为本页面，所以需要退一层../
        })
      })
    }

  },

  onLoad: function (options) {
    var currenTime= this.formatTime(new Date());
    this.setData({
      date:currenTime
    })
  },

  formatTime: function(date) {
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return [year, month, day].map(this.formatNumber).join('-');
  },
  formatNumber: function(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },

    /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({
        reid:options.id
      })
    }

  },
  // <img src="http://tmp/wJcdPrxvA1th802484374f3c4a…mg"></img>
})
